package com.example.beryl.proSystem;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.app.AlertDialog;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.beryl.R;
import com.example.beryl.Util.HandlePublic;
import com.example.beryl.Util.ReceiveBroadCast;
import com.example.beryl.entity.Action;
import com.example.beryl.entity.Cutting.BarCode;
import com.example.beryl.entity.UserData.EQ;
import com.example.beryl.entity.UserData.Person;
import com.example.beryl.http.Net_cuttingStart;
import com.example.beryl.http.Net_userData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 裁切开单
 */
public class cuttingStart extends AppCompatActivity {
   private TextView textView;
    private Toolbar toolbar;
    private ConstraintLayout clMain;
   private EditText editText;
   private EditText editText1;
   private EditText editText2;
   private EditText editText3;
   private EditText editText4;
   private EditText editText5;
   private EditText editText6;
   private EditText editText7;
   private EditText editText9;
   private EditText editText10;
   private Button btn;
   private String KnResult = "";
   private String PersonNum = "";
   private Net_cuttingStart dbUtil;
   private boolean mReceiverTag = false;//广播注册标志
    private String KnStage = "";
   //新建全局广播对象
    ReceiveBroadCast mBroadcastReceiver = new ReceiveBroadCast();
    HandlePublic handlePublic = new HandlePublic();
    private static final int CQD = 1;
    private static final int DJ = 2;
    private static final int EQ =3;
    private static final int EM =4;
    private static final int recal = 5;
   //注册广播地址
    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        mReceiverTag = true;
        filter.addAction("com.android.server.scannerservice.broadcast"); //添加过滤条件，接收广播
        registerReceiver(mBroadcastReceiver, filter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //取消系统title
        //supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_cutting_start);
        toolbar = findViewById(R.id.toolbar);
        clMain = findViewById(R.id.cl_main);
        setSupportActionBar(toolbar);
        toolbar.setTitle("裁切开单");
        toolbar.setNavigationIcon(R.drawable.ic_baseline_arrow_back);
        toolbar.setNavigationOnClickListener(view -> finish());
        toolbar.setOnMenuItemClickListener(item -> {
            switch (item.getGroupId()){
                case 0:
                case 1:
                case 2:
                case 3:{
                    Toast.makeText(cuttingStart.this, "点了一下"+item.getTitle(), Toast.LENGTH_SHORT).show();
                    break;
                }
            }
            return false;
        });

        //绑定按钮
        editText = findViewById(R.id.Edit_account);
        editText1 = findViewById(R.id.kn);
        editText2 = findViewById(R.id.productnum);
        editText3 = findViewById(R.id.caiqielongT);
        editText4 = findViewById(R.id.chuchangnumT);
        editText5 = findViewById(R.id.youxiaochangduT);
        editText6 = findViewById(R.id.mianjiT);
        editText7 = findViewById(R.id.birongT);
        editText9 = findViewById(R.id.yuangongnumT);
        editText10 = findViewById(R.id.shebeinum);

        //禁止editView手动编辑
        editText.setEnabled(false);
        editText1.setEnabled(false);
        editText2.setEnabled(false);
        editText3.setEnabled(false);
        editText4.setEnabled(false);
        editText5.setEnabled(false);
        editText6.setEnabled(false);
        editText7.setEnabled(false);
        //editText9.setEnabled(false);
        editText10.setEnabled(false);
        btn = findViewById(R.id.submit);
        dbUtil = new Net_cuttingStart();
        if (Action.person != null)
        {
            editText9.setText(Action.person.cPsn_Name);
        }
       //editView值发生变化后的操作
       editText.addTextChangedListener(new TextWatcher() {
           @Override
           public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

           }
           @Override
           public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

               String t = charSequence.toString();
               if (t.equals(""))
               {
                   System.out.println("为空");
               }else
               {
                   //handlePublic.startLoad(cuttingStart.this);
                   new Thread(() -> getBarCode()).start();
               }
           }
           @Override
           public void afterTextChanged(Editable editable) {
           }
       });

        //输入工号查询
        editText9.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() == 4)
                {
                    boolean T = handlePublic.isNumericZidai(charSequence.toString());
                    if (T)
                    {
                        String PersonNUm = "EM-" + charSequence.toString();
                        DataResult(PersonNUm);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
       //点击提交按钮操作
       btn.setOnClickListener(view -> {
           AlertDialog.Builder builder = new AlertDialog.Builder(cuttingStart.this);
           builder.setTitle("提示");
           builder.setMessage("是否提交数据");
           builder.setPositiveButton("是", (dialogInterface, i) ->  summitData());
           builder.setNegativeButton("否",
                   (dialog, which) -> dialog.dismiss());
           builder.create().show();

       });
       //结果回调函数
       mBroadcastReceiver.setScanHeadListener(code -> DataResult(code));

       //网络查询结果handler公共通知
       handlePublic.setGetResult((what, t) -> {
           gethandle(what,t);
       });
    }
    //扫描结果返回处理
    private void DataResult(String data)
    {

        switch (data.substring(0,2))
        {
            case "WO":
                editText.setText(data);
                break;
            case "DZ":
                if (editText.getText().toString().equals(""))
                {
                    handlePublic.Alert("请先扫描裁切单!",this);
                }else
                {
                   // handlePublic.startLoad(cuttingStart.this);
                    new Thread(() -> getKn(data)).start();
                }
                break;
            case "EQ":
            case "EM":
               // handlePublic.startLoad(cuttingStart.this);
                new Thread(() -> getPenson(data)).start();
                break;
        }
    }

    private void gethandle(int what,Object t)
    {
        String ret = handlePublic.dealDataBase((List)t);
        if (ret.contains("[") || ret.contains("{"))
        {
            switch (what)
            {
                case CQD://裁切单
                    BarCode barCode = (BarCode) handlePublic.getEntity(ret,BarCode.class);
                    editText2.setText(barCode.cMOLotNo);
                    String CQL = barCode.leng;
                    editText3.setText(CQL);
                    String CCN = barCode.cBatchNumber;
                    editText4.setText(CCN);
                    String HD = barCode.dEffWidth;
                    editText5.setText(HD);
                    String MJ = barCode.dLotQty;
                    editText6.setText(MJ);
                    String BR = barCode.cxx;
                    String BR1 = barCode.csx;
                    editText7.setText(BR + "-" + BR1);
                    break;
                case DJ:
                    String status = handlePublic.ChangeString(ret);
                    switch (status)
                    {
                        case "0":
                        case "1":
                            editText1.setText(KnResult);
                            break;
                        case "2":
                            handlePublic.Alert("裁切单长度已超过刀具标准长度!",this);
                            break;
                    }
                    KnStage = status;
                    break;
                case EQ:
                    EQ eq = (com.example.beryl.entity.UserData.EQ) handlePublic.getEntity(ret,com.example.beryl.entity.UserData.EQ.class);
                    editText10.setText(eq.cSuperviseNo);
                    break;
                case EM:
                    Person EM = (Person) handlePublic.getEntity(ret,Person.class);
                    Action.person = EM;
                    editText9.setText(EM.cPsn_Name);
                    PersonNum = EM.cPsn_Num;
                    break;
                case recal:
                    handlePublic.Alert("提交成功",this);
                    editText.setText("");
                    editText1.setText("");
                    editText2.setText("");
                    editText3.setText("");
                    editText4.setText("");
                    editText5.setText("");
                    editText6.setText("");
                    editText7.setText("");
                    editText9.setText("");
                    editText10.setText("");
                    KnResult = "";
                    KnStage = "";
                    PersonNum = "";
                    break;
            }
        }
        else
        {
            handlePublic.Alert(ret,this);
        }
    }

    //根据barcode查询数据库
    private void getBarCode()
    {
        List<String> list = new ArrayList<String>();
        list = dbUtil.CS_CommonMethod(Action.action.GetBarcode,editText.getText().toString());
        handlePublic.setmHandler(CQD,list);
    }

    private void getKn(String data)
    {
        List<String> list;
        HashMap<String,String> hashMap = new HashMap<>();
        hashMap.put("长度",editText3.getText().toString());
        hashMap.put("刀具",data);
        String json = handlePublic.MakeJson(hashMap);
        System.out.println(json);
        list = dbUtil.CS_CommonMethod(Action.action.GetKn,json);
        KnResult = data.split("-")[1];
        handlePublic.setmHandler(DJ,list);
    }

    private void getPenson(String data)
    {
        String T = data.split("-")[0];
        Net_userData userData = new Net_userData();
        if (T.equals("EQ"))
        {
            HashMap<String,String> hashMap = new HashMap<>();
            hashMap.put("设备",data);
            hashMap.put("参数","裁切");
            String json = handlePublic.MakeJson(hashMap);
            List<String> list = new ArrayList<>();
            list = userData.User_CommonMethod(Action.action.GetEM,json);
            handlePublic.setmHandler(EQ,list);
        }else
        {
            List<String> list;
            list = userData.User_CommonMethod(Action.action.GetPerson,data.split("-")[1]);
            handlePublic.setmHandler(EM,list);
        }
    }
    //提交逻辑
    private void summitData()
    {
            HashMap<String,String> dict = new HashMap<>();
            dict.put("cBarCode",editText.getText().toString());
            dict.put("cMOLotNo",editText2.getText().toString());
            dict.put("cStartTotalLength",editText3.getText().toString());
            dict.put("cToolNo",editText1.getText().toString());
            dict.put("cEqNo",editText10.getText().toString());
            dict.put("cPsNo",PersonNum);
            dict.put("cPsName",editText9.getText().toString());
            dict.put("cCreateTime", handlePublic.Date(1));
            dict.put("isComplete","0");

//            dict.put("cBarCode","1");
//            dict.put("cMOLotNo","1");
//            dict.put("cStartTotalLength","1");
//            dict.put("cToolNo","1");
//            dict.put("cEqNo","1");
//            dict.put("cPsNo","1");
//            dict.put("cPsName","1");
//            dict.put("cCreateTime", "1");
//            dict.put("isComplete","0");

            if(dict.containsValue("")) {
                handlePublic.Alert("请把表格输入完整",this);
            }
            else
            {
                String josn = handlePublic.MakeJson(dict);
                System.out.println(josn);
                //handlePublic.startLoad(cuttingStart.this);
                new Thread(() -> {
                    List<String> list;
                    list = dbUtil.CS_CommonMethod(Action.action.CS_Summit,josn);
                    handlePublic.setmHandler(recal,list);
                }).start();
            }
    }
    //按返回键时要反注册广播
    @Override
    public void onBackPressed() {
        if (mReceiverTag) {
            unregisterReceiver(mBroadcastReceiver);
            finish();
        }
    }
    //状态栏菜单显示
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_menu, menu);
        //MenuItem menuItem = menu.findItem(R.id.toolbar_user);
        //menuItem.setVisible(false);
        setVisible(true);
        return true;
    }

    //弹出提示
//    private void Alert(String Message)
//    {
//        AlertDialog.Builder builder = new AlertDialog.Builder(cuttingStart.this);
//        builder.setTitle("信息");
//        builder.setMessage(Message);
////                        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
////                            @Override
////                            public void onClick(DialogInterface dialogInterface, int i) {
////                                finish();
////                            }
////                        });
//        builder.setNegativeButton("确定",
//                new DialogInterface.OnClickListener() {
//
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                    }
//                });
//        builder.create().show();
//    }

}